from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from pathlib import Path
from datetime import datetime
from util.log_util import logs_info,logs_error,logs_debug
import os




class Base:
    """
    Selenium 基础操作封装类
    功能：
    1. 元素等待操作
    2. 自动日志记录
    3. 基础浏览器操作
    """
    
    def __init__(self, driver, timeout=10, poll_frequency=0.5):
        """
        初始化配置
        :param driver: WebDriver实例
        :param timeout: 显式等待超时时间(秒)
        :param poll_frequency: 轮询间隔(秒)
        """
        self.driver = driver
        self.timeout = timeout
        self.poll_frequency = poll_frequency
        self.wait = WebDriverWait(self.driver, self.timeout, self.poll_frequency)
        
    def open(self,url):
        """
        打开指定URL并最大化窗口
        :param url: 要访问的网址
        """
        try:
            logs_info(f"打开网址: {url}")
            self.driver.get(url)
            logs_info(f"网址 {url} 访问成功")
        except Exception as e:
            logs_error(f"网址 {url} 访问失败,失败原因: {str(e)}")
            raise

    def find(self,locator):
        """
        选择单个元素
        :return: 元素
        """
        try:
            logs_debug(f"选择元素: {locator}")
            return self.wait.until(EC.visibility_of_element_located(locator))    
        except Exception as e:
            logs_error(f"未发现元素: {locator},失败原因: {str(e)}")

    def finds(self,locator):
        """
        选择多个元素
        :return: 元素
        """
        try:
            logs_debug(f"选择元素: {locator}")
            return self.wait.until(EC.visibility_of_all_elements_located(locator))
        except Exception as e:
            logs_error(f"未发现元素: {locator},失败原因: {str(e)}")

    def presence(self,locator):
        """
        选择单个元素
        :return: 元素
        """
        try:
            logs_debug(f"选择元素: {locator}")
            return self.wait.until(EC.presence_of_element_located(locator))
        except Exception as e:
            logs_error(f"未发现元素: {locator},失败原因: {str(e)}")

    def presences(self,locator):
        """
        选择多个元素
        :return: 元素
        """
        try:
            logs_debug(f"选择元素: {locator}")
            return self.wait.until(EC.presence_of_all_elements_located(locator))
        except Exception as e:
            logs_error(f"未发现元素: {locator},失败原因: {str(e)}")
            
    def click(self, locator):
        """
        点击元素（带显式等待）
        :param locator: 元素定位元组 (By.XXX, 'value')
        """
        try:
            self.wait.until(EC.element_to_be_clickable(locator)).click()
            logs_info(f"点击元素: {locator}")
        except Exception as e:
            logs_error(f"点击元素失败 {locator}: {str(e)}")
            raise

    def input(self, locator, text):
        """
        输入文本（带显式等待）
        :param locator: 元素定位元组
        :param text: 要输入的文本
        """
        try:
            element = self.wait.until(EC.visibility_of_element_located(locator))
            element.clear()
            element.send_keys(text)
            logs_info(f"元素 {locator} 中输入 {text}")
        except Exception as e:
            logs_error(f"元素 {locator} 输入错误: {str(e)}")
            raise
        
    def get_text(self, locator):
        """
        获取元素文本
        :return: 元素文本内容
        """
        try:
            text = self.wait.until(EC.visibility_of_element_located(locator)).text
            logs_debug(f" 从元素: {locator} 获取文本 '{text}'")
            return text
        except Exception as e:
            logs_error(f"从元素 {locator} 获取文本失败: {str(e)} ")
            raise

    def get_text_elm(self,elm):
        """
        获取元素文本
        参数为元素
        :return: 元素文本内容
        """
        try:
            text = elm.text
            logs_debug(f"元素获取文本 {text.replace('\n', '、').replace('\r', '、')} '")
            return text
        except Exception as e:
            logs_error(f"元素获取文本失败: {str(e)} ")
            raise

    def take_screenshot(self, screenshot_dir="D://img/temperature_monitoring", name_prefix="screenshot"):
        """
        自动截取浏览器当前页面并保存到指定目录
        参数:
            driver: WebDriver 实例
            screenshot_dir: 截图保存目录（默认'D://img/temperature_monitoring')
            name_prefix: 截图文件名前缀（默认'screenshot')
        返回:
            str: 截图文件的完整路径
        异常:
            WebDriverException: 截图失败时抛出
        """
    # 1. 创建截图目录（如果不存在）
        os.makedirs(screenshot_dir, exist_ok=True)
        # 2. 生成带时间戳的文件名
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"{name_prefix}_{timestamp}.png"
        filepath = os.path.join(screenshot_dir, filename)
        # 3. 尝试截图
        # 实际截图操作
        self.driver.save_screenshot(filepath)
      
    def get_title(self):
        """
        获取页面标题
        :return: 当前页面标题
        """
        try:
            title = self.driver.title
            logs_info(f"获取页面标题成功: {title}")
            return title
        except Exception as e:
            logs_error(f"获取页面标题失败: {str(e)}")
            raise

    def page_back(self):
        """
        页面回退
        """
        try:
            self.driver.back()
            logs_info('页面回退成功')
        except Exception as e:
            logs_error(f"页面回退失败: {str(e)}")
            raise

    def assert_equal(self,var1,var2):
        try:
            assert var1 == var2
            logs_info(f'页面值：{var1}  期望值:{var2}')
        except Exception as e:
            logs_error(f'页面值：{var1}  期望值:{var2}')
            self.take_screenshot()